package com.hanlyjiang.library.components;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanlyjiang.library.R;


/**
 * 拥有一个Toolbar 的 Activity
 * @author hanlyjiang on 2017/6/1-下午7:19.
 * @version 1.0
 */

public abstract class ActivityWithToolbar extends AppCompatActivity {

    private LinearLayout parentLayout;

    private Toolbar toolbar;

    private TextView titleView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(getResources().getColor(R.color.main_blue));
        }
        setTitleContentView(getLayoutId());
        initView();
        setEventListener();
    }

    public abstract @LayoutRes
    int getLayoutId();
    public abstract void initView();

    public void setEventListener() {}

    public void setTitleContentView(@LayoutRes int layoutResID) {
        parentLayout= new LinearLayout(this);
        ViewGroup viewGroup = (ViewGroup) findViewById(android.R.id.content);
        viewGroup.removeAllViews();
        parentLayout.setOrientation(LinearLayout.VERTICAL);
        viewGroup.addView(parentLayout);
        parentLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.tool_bar, parentLayout, true);
        View content = View.inflate(this, layoutResID, parentLayout);
        super.setContentView(content);
        initTitle();
    }

    private void initTitle() {
        toolbar = (Toolbar) parentLayout.findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setVisibility(View.GONE);
    }

    public void setTitle(String title) {
        toolbar.setVisibility(View.VISIBLE);
        titleView = (TextView) parentLayout.findViewById(R.id.toolbar_center_title);
        titleView.setText(title);
    }

    public void setTitle(int resId) {
        toolbar.setVisibility(View.VISIBLE);
        titleView = (TextView) parentLayout.findViewById(R.id.toolbar_center_title);
        titleView.setText(resId);
    }
}
